// pages/recipe/add/add.js
Page({
  data: {
    userInfo:{},
    types:'add',
    _id:'',
    showDialog1:false,
    db:null,
    count:0, // 库存
    image: '', // 菜谱图片
    name: '', // 菜谱名称
    categories: [],
    categoryIndex: 0, // 当前选中的分类索引
    categoryName:'',
    createTime:'',
    price: '', // 菜谱价格
    rate: 5, // 默认3星
    typeId:'',
    statusList: [],
    status: '正常', // 默认状态
    description: '', // 菜谱描述
    isPublic: true, // 是否公开
  },
  onLoad(options) {
    console.log('options',options)

    this.setData({ 
      loading: true,
      userInfo:wx.getStorageSync('userInfo')
    });
    // 在任何页面/组件中获取
    const app = getApp();
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })
    this.data.db.collection('type').orderBy('order','asc')
    .where({
      _openid:this.data.userInfo._openid
    })
    .get()
    .then(res => {
      console.log('res',res)
      if(res && res.data && res.data.length > 0){
        this.setData({
          categories:res.data,
        })
        if(options && options.id){
          this.setData({
            _id:options.id
          })

          this.loadCategoryData(options.id)
        }
      }else{
        wx.showToast({ title: '加载分类数据为空', icon: 'none' })
        this.setData({ loading: false });
      }
    })
    .catch(err => {
      wx.showToast({ title: '加载分类数据失败', icon: 'none' })
      this.setData({ loading: false });
    })
  },
  getFormats(timestamp) {
    const date = new Date(timestamp);
  
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  loadCategoryData(_id) {
    wx.showLoading({
      title: '加载中...',
    })
    this.data.db.collection('message')
    .where({
      _id: _id
    })
    // .orderBy('createTime', 'desc')
    .get()
    .then(res => {
      console.log('res',res)
      if(res && res.data && res.data.length === 1){
        this.setData({
          image: res.data[0].image, // 菜谱图片
          name: res.data[0].name, // 菜谱名称
          rate: res.data[0].rate, // 默认3星
          createTime:this.getFormats(res.data[0].createTime),
          typeId:res.data[0].typeId,
          status: res.data[0].status, // 默认状态
          description:res.data[0].description, // 菜谱描述
          _id:res.data[0]._id
        })
        console.log('index this.data.categories',this.data.categories)
        const arr = this.data.categories.filter(item => item._id === res.data[0].typeId);
        if(arr && arr.length > 0){
          this.setData({
            categoryName:arr[0].name
          })
        }

      }else{
        wx.showToast({ title: '加载数据为空', icon: 'none' })
      }
    })
    .catch(err => {
      wx.showToast({ title: '加载数据失败', icon: 'none' })
    }).finally(( ) => {
      wx.hideLoading()
    })
    return;
    this.setData({ loading: true });
    

    // 模拟API请求
    setTimeout(() => {
      const mockData = this.generateMockData();
      this.setData({
        categories: mockData,
        loading: false
      });
      console.log('mockData',mockData)
    }, 800);
  },
   // 预览图片
   previewImage() {
    wx.previewImage({
      urls: [this.data.image], // 需要预览的图片链接列表
      current: this.data.image, // 当前显示图片的链接
      success: (res) => {
        console.log('预览成功');
      },
      fail: (err) => {
        console.log('预览失败', err);
      }
    });
  },

  // 下载图片
  downloadImage() {
    wx.showLoading({
      title: '下载中...',
    });

    wx.downloadFile({
      url: this.data.image,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.hideLoading();
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              });
            },
            fail: (err) => {
              wx.hideLoading();
              console.log('保存失败', err);
            }
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.log('下载失败', err);
      }
    });
  }
})